Page({
  data: {
    schema:[
    ],
    formData:{
    },
    title: '',
    result: '',
    remark: '',
    apiName: '',
    direction: 0,       // 方向角度
    isRunning: false,   // 指南针是否正在运行
    accuracy: 0         // 精度
  },
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: options.title,
    })
    
    this.setData({
      title: options.title,
      zh:options.zh,
      remark: options.remark,
      webUrl: options.webUrl
    })
  // 页面加载时检查是否有指南针权限
  this.checkCompassPermission();
  },
  // 检查指南针权限
  checkCompassPermission() {
    wx.getSetting({
      success: (res) => {
        // 如果没有获取过设备方向权限，请求授权
        if (!res.authSetting['scope.deviceOrientation']) {
          wx.authorize({
            scope: 'scope.deviceOrientation',
            success: () => {
              console.log('授权成功');
            },
            fail: () => {
              console.log('授权失败');
              wx.showToast({
                title: '需要指南针权限',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  // 启动指南针
  startCompass(e) {
    const that = this;
    
    // 启动指南针
    wx.startCompass({
      success: (res1) => {
        console.log('指南针已启动');
        that.setData({ isRunning: true });
        that.setData({
          result: res1,
          apiName: e.currentTarget.dataset.apiname
        })
        // 监听指南针数据变化
        this.compassWatch = wx.onCompassChange((res) => {
          that.setData({
            direction: res.direction.toFixed(1),
            accuracy: res.accuracy
          });
        });
      },
      fail: (err) => {
        console.error('启动指南针失败', err);
        this.setData({
          result: err,
          apiName: e.currentTarget.dataset.apiname
        })
        wx.showToast({
          title: '启动失败',
          icon: 'none'
        });
      }
    });
  },

  // 停止指南针
  stopCompass(e) {
    wx.stopCompass({
      success: (res) => {
        console.log('指南针已停止');
        this.setData({ isRunning: false });
        this.setData({
          result: res,
          apiName: e.currentTarget.dataset.apiname
        })
        // 移除监听
        wx.offCompassChange();
      }
    });
  },
  onCompassChange(e){
    this.compassWatch =wx.onCompassChange((res) => {
      this.setData({
        result: res,
        apiName: e.currentTarget.dataset.apiname
      })
    })
  },
  offCompassChange(e){
    wx.offCompassChange(this.compassWatch)
      this.setData({
        result: "移除罗盘数据变化事件的监听函数",
        apiName: e.currentTarget.dataset.apiname
      })
    
  },
  // 生命周期函数--监听页面卸载
  onUnload() {
    // 页面卸载时停止指南针
    if (this.data.isRunning) {
      wx.stopCompass();
      wx.offCompassChange();
    }
  }
})
